package org.wupgame.repository;

import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
import org.wupgame.model.Room;


@Repository
public interface RoomRepository extends JpaRepository<Room, String> {
	
	@Query(value = "select r from Room r")
	Page<Room> findAllRoom(Pageable pageable);
	
	@Query(value = "select r from Room r where r.id = :id")
	Room findRoomById(@Param("id") String id);
	
	@Query(value = "select r from Room r where r.gameStart= false ")
	Page<Room> findAllNotStartRoom(Pageable pageable);
	
	@Transactional
	@Modifying
	@Query(value = "insert into Room (id,roomName,gameStart,maxPlayer,player,roomPassword)values (:id,:name,false,:maxPlayer,1,:password )")
	void insertRoom(
		@Param("id") String id,
		@Param("name") String name,
		@Param("password") String password,
		@Param("maxPlayer") int maxPlayer);
	
	@Transactional
	@Modifying
	@Query(value = "update Room r set r.roomName = :name where r.id = :id")
	void updateRoomName(
		@Param("name") String name,
		@Param("id") String id);
	
	@Transactional
	@Modifying
	@Query(value = "update Room r set r.player = r.player +1 where r.id = :id")
	void plusPlayerCount(
		@Param("id") String id);
	
	@Transactional
	@Modifying
	@Query(value = "update Room r set r.player = r.player -1 where r.id = :id")
	void reducePlayerCount(
		@Param("id") String id);
	
	@Transactional
	@Modifying
	@Query(value = "update Room r set r.gameStart = true where r.id = :id")
	void gameStart(@Param("id") String id);
	
	@Transactional
	@Modifying
	@Query(value = "update Room r set r.gameStart = false where r.id = :id")
	void gameOver(@Param("id") String id);
	
	@Transactional
	@Modifying
	@Query(value = "delete from Room r where r.id = :id ")
	void deleteRoom(@Param("id") String id);
}